import os
import traceback

import paramiko
import shutil


def sync_local_to_remote(local_folder, remote_host, remote_user, remote_password, remote_folder, remote_port=22):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程服务器
        ssh.connect(remote_host, port=remote_port, username=remote_user, password=remote_password)

        # 使用SFTP进行文件传输
        sftp = ssh.open_sftp()

        # 遍历本地文件夹
        for root, dirs, files in os.walk(local_folder):
            # 计算相对路径
            relative_path = os.path.relpath(root, local_folder)
            remote_root = os.path.join(remote_folder, relative_path)

            # 在远程创建对应目录
            if dirs:
                try:
                    sftp.mkdir(remote_root, ignore_existing=True)
                except IOError:
                    pass  # 目录可能已存在，忽略错误

            # 上传文件
            for file in files:
                local_file = os.path.join(root, file)
                remote_file = os.path.join(remote_root, file)

                # 确保目录存在后上传文件
                if not sftp.exists(os.path.dirname(remote_file)):
                    sftp.mkdir(os.path.dirname(remote_file), ignore_existing=True)

                sftp.put(local_file, remote_file)
                print(f"上传完成: {local_file} -> {remote_file}")

    except Exception as e:
        print(f"同步过程中发生错误: {str(e)}")
        print(traceback.format_exc())
    finally:
        # 关闭连接
        sftp.close()
        ssh.close()


# 使用示例
local_folder = r'D:\data\231207huoni\test_data\test_sync_dir'
remote_host =  '192.168.6.14'
remote_user = 'ps'
remote_password = '1'
remote_folder = '/home/ps/zhangxiancai/data/231207huoni/test_data/snyc_dir_test'

sync_local_to_remote(local_folder, remote_host, remote_user, remote_password, remote_folder)
